package com.emm.yixun.estate.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.WebService;

import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.enums.ModelEnum;
import com.emm.yixun.basic.service.BaseCodeTypeService;
import com.emm.yixun.basic.service.BaseCodeValueService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.ModelKeyService;
import com.emm.yixun.basic.service.ProjectBuildingService;
import com.emm.yixun.basic.service.ProjectCarareaService;
import com.emm.yixun.basic.service.ProjectCarportService;
import com.emm.yixun.basic.service.ProjectInfoService;
import com.emm.yixun.basic.service.ProjectPmoService;
import com.emm.yixun.basic.service.ProjectPremisesIndustDataService;
import com.emm.yixun.basic.service.ProjectPremisesPmoService;
import com.emm.yixun.basic.service.ProjectPremisesService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.ProjectUnitService;
import com.emm.yixun.basic.service.SaleReturnPmoService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.CustomerLevelEnum;
import com.emm.yixun.common.enums.IndustMarkEnums;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.pmo.ClientData;
import com.emm.yixun.common.model.pmo.DynamiSalesData;
import com.emm.yixun.common.model.pmo.DynamiSalesDataExtend;
import com.emm.yixun.common.model.pmo.DynamiSalesFieldIndustData;
import com.emm.yixun.common.model.pmo.DynamiSalesIndustData;
import com.emm.yixun.common.model.pmo.GraphicalVo;
import com.emm.yixun.common.model.pmo.LevelDynamiSalesData;
import com.emm.yixun.common.model.pmo.LevelStaticIndustMark;
import com.emm.yixun.common.model.pmo.LevelStaticIndustMarkParam;
import com.emm.yixun.common.model.pmo.PmoReportDto;
import com.emm.yixun.common.model.pmo.TargetValue;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.MathUtil;
import com.emm.yixun.estate.service.ProjectServiceFacade;

@Service("projectServiceFacade")
@WebService(name = "com.emm.yixun.estate.service.ProjectServiceFacade")
public class ProjectServiceFacadeImpl implements ProjectServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ProjectService service;

	@Autowired
	private ProjectPremisesService projectPremisesService;

	@Autowired
	private ProjectBuildingService projectBuildingService;

	@Autowired
	private ProjectUnitService projectUnitService;

	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private ProjectCarareaService projectCarareaService;
	@Autowired
	private ProjectCarportService projectCarportService;
	@Autowired
	private ProjectInfoService projectInfoService;

	@Autowired
	private ProjectPmoService projectPmoService;

	@Resource
	private ModelKeyService modelKeyService;

	@Autowired
	private DataPermissionService dataPermissionService;

	@Autowired
	private ProjectSettingService projectSettingService;

	@Autowired
	private ProjectPremisesIndustDataService projectPremisesIndustDataService;

	@Autowired
	private ProjectPremisesPmoService projectPremisesPmoService;

	@Autowired
	private SaleReturnPmoService salereturnpmoservice;

	@Autowired
	private BaseCodeValueService baseCodeValueService;

	@Autowired
	private BaseCodeTypeService baseCodeTypeService;

	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private SignedService signedService;
	
	
	

	@Override
	public Response<ProjectDto> save(ProjectDto projectDto, ProjectInfoDto projectInfoDto,
			ProjectSettingDto projectSettingDto, ProjectPmoDto projectPmoDto) {
		Response<ProjectDto> response = new Response<ProjectDto>();
		try {
			if (null == projectDto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			// 新增时需要生成项目编号
			if (null == projectDto.getId()) {
				projectDto.setProjectCode(modelKeyService.next(ModelEnum.PROJECT));
				// 保存项目基本信息
				projectDto.setAccessCode(projectDto.getProjectCode());
			} else {
				Project pro = service.selectById(projectDto.getId());
				projectDto.setProjectCode(pro.getProjectCode());
			}
			if (StringUtils.isEmpty(projectDto.getProjectName()) && null != projectPmoDto) {
				projectDto.setProjectName(projectPmoDto.getPromotName());
			}
			//存在Id,标识修改
			String oldName = "";
			String newName = projectDto.getProjectName();
			boolean needUpdateRoomName = false;
			if (null != projectDto.getId()) {
				//获取原项目信息,记录原项目名称
				//判断修改名称与原名称是否一致
				//不一致,修改所有房间号别名
				Project oldProject = service.selectById(projectDto.getId());
				oldName = oldProject.getProjectName();
				if(!oldName.equals(newName)){
					needUpdateRoomName = true;
				}
			}

			ProjectDto mDto = service.create(projectDto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}

			Long projectId = mDto.getId();
			//修改所有房源名称
			if(needUpdateRoomName){
				int count = service.updateCombinedNameByProjectId(oldName, newName, projectId);
				logger.info("修改项目下房间别名: 由" + oldName + "变更至" + newName + ",总计修复" + count + "笔。");
			}

			if (null == projectInfoDto.getId()) {
				projectInfoDto.setProjectCode(projectDto.getProjectCode());
				projectInfoDto.setProjectId(projectId);
				projectInfoDto.setAccessCode(projectDto.getProjectCode());
				projectInfoDto.setProjectInfoCode(modelKeyService.next(ModelEnum.PROJECT_INFO));
			}
			if (null == projectSettingDto.getId()) {
				projectSettingDto.setProjectCode(projectDto.getProjectCode());
				projectSettingDto.setProjectId(projectId);
				projectSettingDto.setAccessCode(projectDto.getProjectCode());
				projectSettingDto.setSettingCode(modelKeyService.next(ModelEnum.PROJECT_SETTING));
			}
			projectInfoService.create(projectInfoDto);
			projectSettingService.create(projectSettingDto);

			if (null != projectPmoDto) {
				if (null == projectPmoDto.getId()) {
					// 新增
					// 项目ID
					projectPmoDto.setProjectId(projectId);
					projectPmoService.create(projectPmoDto);
				} else {
					// 修改
					projectPmoService.update(projectPmoDto);
				}
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(ProjectDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			ProjectDto mDto = new ProjectDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Project> findById(Long id) {
		Response<Project> response = new Response<Project>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Project entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Project> findByDto(ProjectDto dto) {
		ResponseList<Project> response = new ResponseList<Project>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			if (null != dto.getNeedAuth() && "F".equals(dto.getNeedAuth())) {
				// 是否需要权限过滤，当值仅为F的时候，跳过
			} else {
				if (SysConstants.openDataPermission) {
					String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(),
							dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
					String[] dataPermissionArr = dataPermission.split(":");
					if ("00".equals(dataPermissionArr[0])) {
						response.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
						response.setSuccess(false);
						return response;
					}
					// 如果没有任何权限的时候
					String str = dataPermissionArr[1];
					if (StringUtils.isNotEmpty(str) && str.replace(" ", "").length() > 0) {
						dto.setDataPermission(dataPermissionArr[1]);
					} else {
						dto.setDataPermission("AND 1=2");
					}

				}
			}

			List<Project> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<Project> findPageByDto(ProjectDto dto, Integer begin, Integer row) {
		Page<Project> response = new Page<Project>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Project> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<ZNodes> findEstateTree(User user, Long parentId, String level) {
		if (parentId.longValue() == Long.valueOf(-1).longValue())
			parentId = null;
		ResponseList<ZNodes> responseList = new ResponseList<ZNodes>();
		List<ZNodes> list = new ArrayList<ZNodes>();
		if (level.equals("1")) {
			// 查询项目
			list = findProjectTree(user.getMerchantId(), parentId);
			responseList.success(list);
			return responseList;
		} else if (level.equals("2")) {
			// 查询组团或者下级直到找到为止
			// 查询项目组团
			list = findPremisesTree(user.getMerchantId(), parentId);
			// 查询车区
			List<ZNodes> areaList = findCarareaTree(user.getMerchantId(), parentId, "project");
			if (list.size() > 0) {
				if (areaList.size() > 0) {
					for (ZNodes node : areaList) {
						list.add(node);
					}
				}
				responseList.success(list);
				return responseList;
			}

			// 查询项目楼栋
			list = findBuildingTree(user.getMerchantId(), parentId, null);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
			// 查询项目单元
			list = findUnitTree(user.getMerchantId(), parentId, null, null);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
			// 查询项目房间
			list = findRoomTree(user.getMerchantId(), parentId, null, null, null);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
		} else if (level.equals("3")) {
			// 查询楼栋或者下级直到找到为止
			// 查询项目楼栋
			list = findBuildingTree(user.getMerchantId(), null, parentId);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
			// 查询项目单元
			list = findUnitTree(user.getMerchantId(), null, parentId, null);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
			// 查询项目房间
			list = findRoomTree(user.getMerchantId(), null, parentId, null, null);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
		} else if (level.equals("4")) {
			// 查询单元或者下级直到找到为止
			// 查询项目单元
			list = findUnitTree(user.getMerchantId(), null, null, parentId);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
			// 查询项目房间
			list = findRoomTree(user.getMerchantId(), null, null, parentId, null);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
		} else if (level.equals("5")) {
			// 查询房间或者下级直到找到为止
			// 查询项目房间
			list = findRoomTree(user.getMerchantId(), null, null, null, parentId);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
		} else if (level.equals("2-1")) {
			// 查询车位
			list = findCarportTree(user.getMerchantId(), parentId);
			if (list.size() > 0) {
				responseList.success(list);
				return responseList;
			}
		}
		responseList.success(list);
		return responseList;
	}

	private List<ZNodes> findRoomTree(Long merchantId, Long projectId, Long premisesId, Long buildingId, Long unitId) {
		ArrayList<ZNodes> result = new ArrayList<ZNodes>();
		ProjectRoomDto projectRoomDto = new ProjectRoomDto();
		projectRoomDto.setProjectId(projectId);
		projectRoomDto.setPremisesId(premisesId);
		projectRoomDto.setBuildingId(buildingId);
		projectRoomDto.setUnitId(unitId);
		projectRoomDto.setMerchantId(merchantId);
		List<ProjectRoom> list = projectRoomService.selectListByDto(projectRoomDto);
		if (null != list) {
			for (ProjectRoom pt : list) {
				ZNodes row = new ZNodes();
				row.setId(String.valueOf("room_" + pt.getId()));
				row.setpId("unit_" + pt.getUnitId());
				row.setName(org.apache.commons.lang.StringUtils.isBlank(pt.getRoomName()) ? "未设置" : pt.getRoomName());
				row.setDetailUrl("/estate/projectRoom/detail");
				// 查询是否存在组团子节点
				row.setIsParent("false");
				// 设置为房间标示
				row.setOther("6");
				result.add(row);
			}
		}
		return result;
	}

	private List<ZNodes> findUnitTree(Long merchantId, Long projectId, Long premisesId, Long buildingId) {
		ArrayList<ZNodes> result = new ArrayList<ZNodes>();
		ProjectUnitDto projectUnitDto = new ProjectUnitDto();
		projectUnitDto.setProjectId(projectId);
		projectUnitDto.setPremisesId(premisesId);
		projectUnitDto.setBuildingId(buildingId);
		projectUnitDto.setMerchantId(merchantId);
		List<ProjectUnit> list = projectUnitService.selectListByDto(projectUnitDto);
		if (null != list) {
			for (ProjectUnit pt : list) {
				ZNodes row = new ZNodes();
				row.setId(String.valueOf("unit_" + pt.getId()));
				row.setpId("building_" + pt.getBuildingId());
				row.setName(org.apache.commons.lang.StringUtils.isBlank(pt.getUnitName()) ? "未设置" : pt.getUnitName());
				row.setDetailUrl("/estate/projectUnit/detail");
				// 查询是否存在组团子节点
				boolean hasChildren = hasChildren(merchantId, pt.getId(), "4");
				row.setIsParent(String.valueOf(hasChildren));
				// 设置为单元标示
				row.setOther("5");
				result.add(row);
			}
		}
		return result;
	}

	private List<ZNodes> findBuildingTree(Long merchantId, Long projectId, Long premisesId) {
		ArrayList<ZNodes> result = new ArrayList<ZNodes>();
		ProjectBuildingDto projectBuildingDto = new ProjectBuildingDto();
		projectBuildingDto.setProjectId(projectId);
		projectBuildingDto.setPremisesId(premisesId);
		projectBuildingDto.setMerchantId(merchantId);
		List<ProjectBuilding> list = projectBuildingService.selectListByDto(projectBuildingDto);
		if (null != list) {
			for (ProjectBuilding pb : list) {
				ZNodes row = new ZNodes();
				row.setId(String.valueOf("building_" + pb.getId()));
				row.setpId("premises_" + pb.getPremisesId());
				row.setName(pb.getBuildingName());
				row.setDetailUrl("/estate/projectBuilding/detail");
				// 查询是否存在组团子节点
				boolean hasChildren = hasChildren(merchantId, pb.getId(), "3");
				row.setIsParent(String.valueOf(hasChildren));
				// 设置为楼栋标示
				row.setOther("4");
				result.add(row);
			}
		}
		return result;
	}

	private List<ZNodes> findPremisesTree(Long merchantId, Long projectId) {
		ArrayList<ZNodes> list = new ArrayList<ZNodes>();
		ProjectPremisesDto projectPremisesDto = new ProjectPremisesDto();
		projectPremisesDto.setMerchantId(merchantId);
		if (null != projectId)
			projectPremisesDto.setProjectId(projectId);
		List<ProjectPremises> listProjectPremises = projectPremisesService.selectListByDto(projectPremisesDto);
		if (null != listProjectPremises) {
			for (ProjectPremises pp : listProjectPremises) {
				ZNodes row = new ZNodes();
				row.setId(String.valueOf("premises_" + pp.getId()));
				row.setpId("project_" + pp.getProjectId());
				row.setName(pp.getGroupName());
				row.setDetailUrl("/estate/projectPremises/detail");
				// 查询是否存在组团子节点
				boolean hasChildren = hasChildren(merchantId, pp.getId(), "2");
				row.setIsParent(String.valueOf(hasChildren));
				// 设置为组团标示
				row.setOther("3");
				list.add(row);
			}
			return list;
		}
		return list;

	}

	// 查询项目层级tree
	private List<ZNodes> findProjectTree(Long merchantId, Long projectId) {
		ArrayList<ZNodes> list = new ArrayList<ZNodes>();
		ProjectDto projectDto = new ProjectDto();
		projectDto.setMerchantId(merchantId);
		if (null != projectId)
			projectDto.setId(projectId);
		List<Project> listProject = service.selectListByDto(projectDto);
		if (null == listProject)
			return list;
		for (Project project : listProject) {
			ZNodes row = new ZNodes();
			row.setId(String.valueOf("project_" + project.getId()));
			row.setpId("0");
			row.setName(project.getProjectName());
			row.setDetailUrl("/estate/project/detail");
			// 查询是否存在组团子节点
			boolean hasChildren = hasChildren(merchantId, project.getId(), "1");
			row.setIsParent(String.valueOf(hasChildren));
			// 设置为项目标示
			row.setOther("2");
			list.add(row);
		}
		return list;
	}

	// 查询车区层级tree
	private List<ZNodes> findCarareaTree(Long merchantId, Long objectId, String type) {
		ArrayList<ZNodes> list = new ArrayList<ZNodes>();
		ProjectCarareaDto areaDto = new ProjectCarareaDto();
		areaDto.setMerchantId(merchantId);
		if (null != objectId) {
			if ("project".equals(type)) {
				// 查询项目下车区
				areaDto.setProjectId(objectId);
			} else if ("premises".equals(type)) {
				// 查询组团下车区
				areaDto.setPremisesId(objectId);
			}
		}
		List<ProjectCararea> carareaList = projectCarareaService.selectListByDto(areaDto);
		if (null == carareaList)
			return list;
		for (ProjectCararea area : carareaList) {
			ZNodes row = new ZNodes();
			row.setId(String.valueOf("cararea_" + area.getId()));
			if ("project".equals(type)) {
				// 查询项目下车区
				row.setpId("project_" + area.getProjectId());
			} else if ("premises".equals(type)) {
				// 查询组团下车区
				row.setpId("premises_" + area.getPremisesId());
			}
			row.setName(area.getCarareaName());
			row.setDetailUrl("/estate/projectCararea/detail");
			// 查询是否存在组团子节点
			boolean hasChildren = hasChildren(merchantId, area.getId(), "2-1");
			row.setIsParent(String.valueOf(hasChildren));
			// 设置为项目标示
			row.setOther("2-1");
			list.add(row);
		}
		return list;
	}

	// 查询车位层级tree
	private List<ZNodes> findCarportTree(Long merchantId, Long carareaId) {
		ArrayList<ZNodes> list = new ArrayList<ZNodes>();
		ProjectCarportDto portDto = new ProjectCarportDto();
		portDto.setMerchantId(merchantId);
		if (null != carareaId) {
			portDto.setCarareaId(carareaId);
		}
		List<ProjectCarport> carportList = projectCarportService.selectListByDto(portDto);
		if (null == carportList)
			return list;
		for (ProjectCarport port : carportList) {
			ZNodes row = new ZNodes();
			row.setId(String.valueOf("carport_" + port.getId()));
			row.setpId("port_" + port.getCarareaId());
			row.setName(port.getCarportName());
			row.setDetailUrl("/estate/projectCarport/detail");
			// 查询是否存在组团子节点
			boolean hasChildren = Boolean.FALSE;
			row.setIsParent(String.valueOf(hasChildren));
			// 设置为项目标示
			row.setOther("3-2");
			list.add(row);
		}
		return list;
	}

	private boolean hasChildren(Long merchantId, Long parentId, String type) {
		if (type.equals("1")) {
			// 某个项目下的组团数量
			int count = findPremisesCount(merchantId, parentId);
			if (count > 0)
				return Boolean.TRUE;
			// 某个组团下的楼栋数量
			count = findBuildingCount(merchantId, parentId, null);
			if (count > 0)
				return Boolean.TRUE;
			// 某个楼栋下的单元数量
			count = findUnitCount(merchantId, parentId, null, null);
			if (count > 0)
				return Boolean.TRUE;
			// 某个单元下的房间数量
			count = findRoomCount(merchantId, parentId, null, null, null);
			if (count > 0)
				return Boolean.TRUE;
		} else if (type.equals("2")) {
			// 某个组团下的楼栋数量
			int count = findBuildingCount(merchantId, null, parentId);
			if (count > 0)
				return Boolean.TRUE;
			// 某个楼栋下的单元数量
			count = findUnitCount(merchantId, null, parentId, null);
			if (count > 0)
				return Boolean.TRUE;
			// 某个单元下的房间数量
			count = findRoomCount(merchantId, null, parentId, null, null);
			if (count > 0)
				return Boolean.TRUE;
		} else if (type.equals("3")) {
			// 某个楼栋下的单元数量
			int count = findUnitCount(merchantId, null, null, parentId);
			if (count > 0)
				return Boolean.TRUE;
			// 某个单元下的房间数量
			count = findRoomCount(merchantId, null, null, parentId, null);
			if (count > 0)
				return Boolean.TRUE;
		} else if (type.equals("4")) {
			// 某个单元下的房间数量
			int count = findRoomCount(merchantId, null, null, null, parentId);
			if (count > 0)
				return Boolean.TRUE;
		} else if (type.equals("2-1")) {
			// 某个车区下的车位数量
			ProjectCarportDto portDto = new ProjectCarportDto();
			portDto.setMerchantId(merchantId);
			portDto.setCarareaId(parentId);
			List<ProjectCarport> portList = projectCarportService.selectListByDto(portDto);
			if (portList.size() > 0)
				return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	// 查询某个项目下的组团数量
	private int findPremisesCount(Long merchantId, Long projectId) {
		ProjectPremisesDto ProjectPremisesDto = new ProjectPremisesDto();
		ProjectPremisesDto.setProjectId(projectId);
		ProjectPremisesDto.setMerchantId(merchantId);
		int count = projectPremisesService.selectCountByDto(ProjectPremisesDto);
		return count;
	}

	// 查询某个组团下的楼栋数量
	private int findBuildingCount(Long merchantId, Long projectId, Long premisesId) {
		ProjectBuildingDto projectBuildingDto = new ProjectBuildingDto();
		projectBuildingDto.setProjectId(projectId);
		projectBuildingDto.setPremisesId(premisesId);
		projectBuildingDto.setMerchantId(merchantId);
		int count = projectBuildingService.selectCountByDto(projectBuildingDto);
		return count;
	}

	// 查询某个楼栋下的单元数量
	private int findUnitCount(Long merchantId, Long projectId, Long premisesId, Long buildingId) {
		ProjectUnitDto projectUnitDto = new ProjectUnitDto();
		projectUnitDto.setProjectId(projectId);
		projectUnitDto.setPremisesId(premisesId);
		projectUnitDto.setBuildingId(buildingId);
		projectUnitDto.setMerchantId(merchantId);
		int count = projectUnitService.selectCountByDto(projectUnitDto);
		return count;
	}

	// 查询某个单元下的房间数量
	private int findRoomCount(Long merchantId, Long projectId, Long premisesId, Long buildingId, Long unitId) {
		ProjectRoomDto projectRoomDto = new ProjectRoomDto();
		projectRoomDto.setProjectId(projectId);
		projectRoomDto.setPremisesId(premisesId);
		projectRoomDto.setBuildingId(buildingId);
		projectRoomDto.setUnitId(unitId);
		projectRoomDto.setMerchantId(merchantId);
		int count = projectRoomService.selectCountByDto(projectRoomDto);
		return count;
	}

	@Override
	public Map<String, String> projectLevelName(long id, String level) {
		Map<String, String> resultMap = new HashMap<String, String>();
		if ("1".equals(level)) {
			// 查询项目
			Project project = service.selectById(id);
			resultMap.put("manageObject", project == null ? "" : project.getProjectName());
			resultMap.put("parentName", project == null ? "" : project.getProjectName());
		} else if ("2".equals(level)) {
			// 查询组团
			ProjectPremises premises = projectPremisesService.selectById(id);
			String premisesName = premises == null ? "" : premises.getGroupName();
			// 项目
			Project project = service.selectById(premises.getProjectId());
			String projectName = project == null ? "" : project.getProjectName();

			resultMap.put("manageObject", projectName + "->" + premisesName);
			resultMap.put("parentName", projectName);
		} else if ("3".equals(level)) {
			// 查询楼栋
			ProjectBuilding building = projectBuildingService.selectById(id);
			String buildingName = building == null ? "" : building.getBuildingName();

			// 楼栋不一定存在组团
			String premisesName = "";
			ProjectPremises premises = null;
			if (StringUtils.isNotEmpty(String.valueOf(building.getPremisesId()))) {
				premises = projectPremisesService.selectById(building.getPremisesId());
				premisesName = premises == null ? "" : premises.getGroupName();
			}

			// 项目
			Project project = service.selectById(building.getProjectId());
			String projectName = project == null ? "" : project.getProjectName();
			// 组装返回参数
			String manageObject = projectName + "->" + premisesName + "->" + buildingName;
			String parentName = projectName + "->" + premisesName;
			if ("".equals(premisesName)) {
				manageObject = projectName + "->" + buildingName;
				parentName = projectName;
			}
			resultMap.put("manageObject", manageObject);
			resultMap.put("parentName", parentName);
		} else if ("4".equals(level)) {
			// 查询单元
			ProjectUnit unit = projectUnitService.selectById(id);
			String unitName = unit == null ? "" : unit.getUnitName();
			// 楼栋
			String buildingName = "";
			if (StringUtils.isNotEmpty(String.valueOf(unit.getBuildingId()))) {
				ProjectBuilding building = projectBuildingService.selectById(unit.getBuildingId());
				buildingName = building == null ? "" : building.getBuildingName();
			}
			// 组团
			String premisesName = "";
			if (StringUtils.isNotEmpty(String.valueOf(unit.getPremisesId()))) {
				ProjectPremises premises = projectPremisesService.selectById(unit.getPremisesId());
				premisesName = premises == null ? "" : premises.getGroupName();
			}
			// 项目
			Project project = service.selectById(unit.getProjectId());
			String projectName = project == null ? "" : project.getProjectName();
			// 组装返回参数
			String manageObject = projectName + "->" + premisesName + "->" + buildingName + "->" + unitName;
			String parentName = projectName + "->" + premisesName + "->" + buildingName;
			if ("".equals(premisesName)) {
				manageObject = projectName + "->" + buildingName + "->" + unitName;
				parentName = projectName + "->" + buildingName;
				if ("".equals(buildingName)) {
					manageObject = projectName + "->" + unitName;
					parentName = projectName;
				}
			} else {
				if ("".equals(buildingName)) {
					manageObject = projectName + "->" + premisesName + "->" + unitName;
					parentName = projectName + "->" + premisesName;
				}
			}
			resultMap.put("manageObject", manageObject);
			resultMap.put("parentName", parentName);
		}
		return resultMap;
	}

	@Override
	public Page<ProjectList> getProjectListPage(ProjectListDto entity, Integer begin, Integer pageSize) {
		Page<ProjectList> response = new Page<ProjectList>();
		response.setPageSize(pageSize);
		try {
			if (null == entity || null == begin || null == pageSize) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}

			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(entity.getPermissionUserId(),
						entity.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				entity.setDataPermission(dataPermissionArr[1]);
			}

			Page<ProjectList> page = service.getProjectListPage(entity, begin, pageSize);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public List<Project> getProjectByUser(User user) {
		List<Project> array = new ArrayList<Project>();
		try {
			ProjectDto projectDto = new ProjectDto();
			projectDto.setDelFlag("0");
			projectDto.setResourcesCode(user.getResourcesCode());
			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(user.getId(),
						projectDto.getResourcesCode(), projectDto.getPrefix(), projectDto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					return array;
				}
				projectDto.setDataPermission(dataPermissionArr[1]);
			}
			projectDto.setMerchantId(user.getMerchantId());
			projectDto.setOrders(" t.create_time desc ");
			array = service.selectListByDto(projectDto);
			return array;
		} catch (Exception e) {
			logger.error("getProjectByUser error: ", e);
		}
		return array;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.emm.yixun.estate.service.ProjectServiceFacade#findReportShiro(java.lang.
	 * Long, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public ResponseList<SalesGroup> findReportShiro(Long userId, String resourcesCode) {
		ResponseList<SalesGroup> responseList = new ResponseList<SalesGroup>();
		responseList.setSuccess(Boolean.FALSE);
		try {
			Map<String, Object> map = dataPermissionService.findReportShiro(userId, resourcesCode);
			if (map != null) {
				if (map.get("salesGroups") != null) {
					responseList.success((ArrayList<SalesGroup>) map.get("salesGroups"));
				} else if (map.get("shiro") != null) {
					responseList.success(new ArrayList<SalesGroup>());
					responseList.setResultMessage("shiro");
				}
			}
		} catch (Exception e) {
			responseList.setResultMessage("报表权限查询失败，用户id:" + userId + ",resourcesCode:" + resourcesCode);
			logger.error("findReportShiro error: ", e);
		}
		return responseList;
	}

	@Override
	public Response<Project> findProjectByCode(String projectCode) {
		Response<Project> response = new Response<Project>();
		try {
			ProjectDto dto = new ProjectDto();
			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			dto.setProjectCode(projectCode);
			Project project = service.selectByDto(dto);
			response.setEntity(project);
			response.setSuccess(true);
		} catch (Exception e) {
			logger.error("查询项目异常:" + e);
			response.setSuccess(false);
		}
		return response;
	}

	@Override
	public Response<LevelDynamiSalesData> quereyLevelDynamiSalesData(String pmoProjectCode, String month) {
		Response<LevelDynamiSalesData> response = new Response<LevelDynamiSalesData>();
		try {
			ProjectPmoDto projectPmoDto = new ProjectPmoDto();
			projectPmoDto.setPmoProjectCode(pmoProjectCode);
			ProjectPmo projectPmo = projectPmoService.selectByDto(projectPmoDto);
			if (null == projectPmo) {
				response.fail("100004", "项目编码:" + pmoProjectCode + "不存在!");
			} else {
				LevelDynamiSalesData levelDynamiSalesData = createLevelDynamiSalesData(projectPmo, month);
				response.success(levelDynamiSalesData);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询动态销售数据:" + e);
			response.fail("000005", "数据库操作异常");
		}
		return response;
	}

	private LevelDynamiSalesData createLevelDynamiSalesData(ProjectPmo projectPmo, String month) {
		Long projectId = projectPmo.getProjectId();
		// 项目级业态动态数据
		List<DynamiSalesDataExtend> list = createIndustDataList(projectId, null, "0", month);
		// 分期级业态动态数据
		List<LevelDynamiSalesData> ztList = createDynamiSalesDatas(projectId, month);
		LevelDynamiSalesData levelDynamiSalesData = new LevelDynamiSalesData();
		levelDynamiSalesData.setProjectCode(projectPmo.getPmoProjectCode());
		levelDynamiSalesData.setLevel("project");
		levelDynamiSalesData.setStageNumber(ztList.size());
		// 组装项目
		levelDynamiSalesData.setData(createDynamiSalesData(list, null, projectId, month));
		// 组装组团
		levelDynamiSalesData.setDynamiSalesDatas(ztList);
		// 组装客户情况
		levelDynamiSalesData.setClientDatas(getClientLevel(projectId, month));
		List<DynamiSalesIndustData> industList =  levelDynamiSalesData.getData().getIndust();
		//如果是月初就继承上月底的数据
		levelDynamiSalesData.getData().setIndust(convertIndustData(industList, projectId));
		// 组装业态
		return levelDynamiSalesData;

	}
	
	
	public List<DynamiSalesIndustData> convertIndustData(List<DynamiSalesIndustData> list,Long projectId) {
		if(list!=null && !list.isEmpty()) {
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
			Map<String, BaseCodeValueDto> bcvMap = baseCodeValueService.selectBcvMap(bcvDto);

			for (DynamiSalesIndustData data : list) {
				Date date = signedService.findMaxSignedCheckDate(projectId, data.getIndustMark());
				if (date != null) {
					String month = DateUtils.DateToString(date, DateStyle.YYYYMM);
					Map<String, Date> map =  dateConvert(month);
					Date beginDate = map.get("beginDate");
					Date endDate = map.get("endDate");
					for (Map.Entry<String, BaseCodeValueDto> entry : bcvMap.entrySet()) {
						bcvDto = entry.getValue();
						if(null != bcvDto && bcvDto.getCodeValue().equals(data.getIndustMark())){
							break;
						}else{
							bcvDto = null;
						}
					}
					if(null == bcvDto){
						continue;
					}
					PmoSaleData sale = 	queryPmoSaleData(projectId, null, bcvDto.getId().toString(), null,beginDate, endDate);
					if(null != sale && sale.getTotalSignAmount()!=null && sale.getTotalCalculateArea().compareTo(BigDecimal.ZERO)!=0) {
						BigDecimal totalSignAmount = sale.getTotalSignAmount().divide(new BigDecimal("10000"));
						if(data.getIndustMark().equals("parkingSpace")) { //车位
							data.getIndustData().setDynamicSalesaveragPrice(MathUtil.bigDivide(totalSignAmount, new BigDecimal(sale.getTotalRowCount()), 2));
						}else {
							data.getIndustData().setDynamicSalesaveragPrice(MathUtil.bigDivide(totalSignAmount, sale.getTotalCalculateArea(), 2));
						}
					}
				}
			}
		}
		return list;
	}

	public List<ClientData> getClientLevel(Long projectId, String month) {
		ClientDataParams params = new ClientDataParams();
		params.setProjectId(projectId);
		Map<String, Date> maps = dateConvert(month);
		Date beginDate = maps.get("beginDate");
		Date endDate = maps.get("endDate");
		params.setStartTime(DateUtils.DateToString(beginDate, DateStyle.YYYY_MM_DD_HH_MM_SS.getValue()));
		params.setEndTime(DateUtils.DateToString(endDate, DateStyle.YYYY_MM_DD_HH_MM_SS.getValue()));
		List<ClientData> list = customerService.queryCustomerLevelByPmo(params);
		if (list != null && !list.isEmpty()) {
			for (ClientData data : list) {
				CustomerLevelEnum level = CustomerLevelEnum.getCustomerLevel(data.getLevel());
				if (level != null) {
					data.setLevel(level.getName());
				}
			}
		}
		return list;
	}

	/**
	 * 
	 * getReasonActualSalesDeviat:销售额偏差原因,回款额偏差原因, 动态货值偏差原因<br/>
	 *
	 * @author Administrator
	 * @param projectId
	 * @param premisesId
	 * @param month
	 * @return
	 * @since JDK 1.6
	 */
	public String getReasonActualSalesDeviat(Long projectId, Long premisesId, String month,
			SaleReturnEnum saleReturnEnum) {
		SaleReturnPmoDto saleReturnPmoDto = new SaleReturnPmoDto();
		if (premisesId != null) {
			saleReturnPmoDto.setObjectId(premisesId);
			saleReturnPmoDto.setObjectType(ObjectTypeEnum.PREMISES.getNo());
		} else {
			saleReturnPmoDto.setObjectId(projectId);
			saleReturnPmoDto.setObjectType(ObjectTypeEnum.PROJECT.getNo());
		}
		saleReturnPmoDto.setSaleReturn(saleReturnEnum.getNo());
		if (saleReturnEnum.getNo().equals("3")) {
			String monthStr = month.substring(4, 6);
			if (monthStr.startsWith("0")) {
				monthStr = month.substring(5, 6);
			} else {
				monthStr = month.substring(4, 6);
			}
			saleReturnPmoDto.setSaleMonth(monthStr);
		} else {
			saleReturnPmoDto.setSaleMonth(month.substring(4, 6));
		}
		saleReturnPmoDto.setSaleYear(month.substring(0, 4));
		List<SaleReturnPmo> srpList = salereturnpmoservice.selectListByDto(saleReturnPmoDto);
		if (null != srpList && srpList.size() > 0) {
			return srpList.get(0).getSaleDiffReason();
		}
		return null;

	}

	/**
	 * 
	 * createDynamiSalesData:(这里用一句话描述这个方法的作用). <br/>
	 * 动态销售数据汇总 项目/分期
	 * 
	 * @author Administrator
	 * @param list
	 * @param premisesId
	 * @param projectId
	 * @param month
	 * @return
	 * @since JDK 1.6
	 */
	private DynamiSalesData createDynamiSalesData(List<DynamiSalesDataExtend> list, Long premisesId, Long projectId,
			String month) {
		DynamiSalesData dsde = new DynamiSalesData();
		dsde.setDynamiExtend(list);
		dsde.setMonth(month);
		// 销售额偏差原因
		dsde.setReasonActualSalesDeviat(getReasonActualSalesDeviat(projectId, premisesId, month, SaleReturnEnum.SALE));
		// 回款额偏差原因
		dsde.setReasonActualBackAmountDeviat(
				getReasonActualSalesDeviat(projectId, premisesId, month, SaleReturnEnum.RETURN));
		// 动态货值偏差原因
		dsde.setReasonDynamiValueDeviat(
				getReasonActualSalesDeviat(projectId, premisesId, month, SaleReturnEnum.DYNAMIC));
		List<DynamiSalesIndustData> indust = new ArrayList<DynamiSalesIndustData>();
		// 动态货值汇总
		BigDecimal roomDynamiValue = BigDecimal.ZERO;
		// 车位动态货值汇总
		BigDecimal carDynamiValue = BigDecimal.ZERO;
		// 未售面积汇总
		BigDecimal unsoldArea = BigDecimal.ZERO;
		// 未售车位汇总
		BigDecimal cwUnsoldParkinSpace = BigDecimal.ZERO;
		// 房间实际销售额
		BigDecimal actualSalesAmount = BigDecimal.ZERO;
		// 车位实际销售额
		BigDecimal carActualSalesAmount = BigDecimal.ZERO;
		BigDecimal totalSalableAcreag = BigDecimal.ZERO;
		for (DynamiSalesDataExtend dynamiSalesDataExtend : list) {
			// 目标货值
			String industMark = dynamiSalesDataExtend.getIndustMark();
			DynamiSalesIndustData dynamiSalesIndustData = new DynamiSalesIndustData();
			dynamiSalesIndustData.setParentId(dynamiSalesDataExtend.getParentId());
			dynamiSalesIndustData.setIndustMark(dynamiSalesDataExtend.getIndustMark());
			DynamiSalesFieldIndustData dynamiSalesFieldIndustData = new DynamiSalesFieldIndustData();
			dsde.setTargetValue(dynamiSalesDataExtend.getTargetValue());
			if (industMark.equals(IndustMarkEnums.INDUSTMARKENUMS_PARKINSPACE.getCode())) {
				// 车位动态货值
				dynamiSalesFieldIndustData
						.setAveragPriceOfParkinSpace(dynamiSalesDataExtend.getAveragPriceOfParkinSpace());
				if (dynamiSalesDataExtend.getCwDynamiAveragPrice() != null) {
					carDynamiValue = carDynamiValue.add(dynamiSalesDataExtend.getCwDynamiAveragPrice());
				}

				if (dynamiSalesDataExtend.getTotalNoCalculateArea() != null) {
					cwUnsoldParkinSpace = cwUnsoldParkinSpace.add(dynamiSalesDataExtend.getTotalNoCalculateArea());
				}
			
				if (dynamiSalesDataExtend.getMonthActualSalesAmount() != null) {
					carActualSalesAmount = carActualSalesAmount.add(dynamiSalesDataExtend.getMonthActualSalesAmount());
				}
				// if (dynamiSalesDataExtend.getLowestAveragPriceInFuture() != null) {
				// dsde.setCwLowestAveragPriceInFuture(
				// new BigDecimal(dynamiSalesDataExtend.getLowestAveragPriceInFuture()));
				// }

			} else {
				if (dynamiSalesDataExtend.getTotalSalableAcreag() != null) {
					totalSalableAcreag = totalSalableAcreag.add(dynamiSalesDataExtend.getTotalSalableAcreag());
				}
				// 房间动态货值
				if (dynamiSalesDataExtend.getDynamiValue() != null)
					roomDynamiValue = roomDynamiValue.add(new BigDecimal(dynamiSalesDataExtend.getDynamiValue()));
				// 动态货值
				dynamiSalesFieldIndustData.setDynamiValue(dynamiSalesDataExtend.getDynamiValue());
				// 已售面积
				dynamiSalesFieldIndustData.setSoldAcreag(dynamiSalesDataExtend.getSoldAcreag());
				// 动态均价
				dynamiSalesFieldIndustData.setDynamiAveragPrice(dynamiSalesDataExtend.getDynamiAveragPrice());
				if (dynamiSalesDataExtend.getMonthActualSalesAmount() != null)
					actualSalesAmount = actualSalesAmount.add(dynamiSalesDataExtend.getMonthActualSalesAmount());
			}
			Map<String, Date> maps = dateConvert(month);
			
			PmoSaleData industMarkSale = queryPmoSaleData(projectId, premisesId, dynamiSalesDataExtend.getId().toString(), null,
					maps.get("beginDate"), maps.get("endDate"));
			if (industMarkSale != null && industMarkSale.getTotalCalculateArea()!=null &&industMarkSale.getTotalCalculateArea().compareTo(BigDecimal.ZERO)!=0) {
				if (industMarkSale.getTotalSignAmount() != null && industMarkSale.getTotalRowCount() != null
						&& industMarkSale.getTotalRowCount().compareTo(0L) != 0) {
					BigDecimal result = MathUtil.divide(industMarkSale.getTotalSignAmount().divide(new BigDecimal("10000")),
							industMarkSale.getTotalCalculateArea());
					dynamiSalesFieldIndustData.setDynamicSalesaveragPrice(result);
				}
			}
			dynamiSalesIndustData.setIndustData(dynamiSalesFieldIndustData);
			indust.add(dynamiSalesIndustData);
		}
		dsde.setIndust(indust);
		// 未售面积 = 可售-已售
		Map<String, Date> maps = dateConvert(month);
		Date beginDate = DateUtils.getCurrYearFirst();
		Date endDate = maps.get("endDate");
		PmoSaleData querySales = queryPmoSaleData(projectId, premisesId, null, "1", beginDate, endDate);
		BigDecimal soldAcreag = null;
		if (querySales != null && querySales.getTotalCalculateArea() != null) {
			soldAcreag = MathUtil.bigDivide(querySales.getTotalCalculateArea(), new BigDecimal("10000"), 6);
		}
		if (soldAcreag == null && totalSalableAcreag != null) {
			unsoldArea = totalSalableAcreag;
		} else if (soldAcreag != null && totalSalableAcreag.compareTo(soldAcreag) > 0) {
			unsoldArea = totalSalableAcreag.subtract(soldAcreag);
		}
		// 已售车位数
		PmoSaleData saleCar = queryPmoSaleData(projectId, premisesId, null, "2", beginDate, endDate);
		if (saleCar.getTotalRowCount() != null && saleCar.getTotalRowCount().compareTo(0L) > 0) {
			dsde.setSoldParkinSpace(saleCar.getTotalRowCount().intValue());
		}
		if (roomDynamiValue.compareTo(BigDecimal.ZERO) != 0 )
			dsde.setDynamiValue(MathUtil.round(roomDynamiValue.add(carDynamiValue), 6)); //动态货值  = 房间动态货值+ 车位动态货值 2018/06/19
		if (carDynamiValue.compareTo(BigDecimal.ZERO) != 0)
			dsde.setCwDynamiValue(carDynamiValue);
		if (soldAcreag != null && soldAcreag.compareTo(BigDecimal.ZERO) != 0)
			dsde.setSoldAcreag(MathUtil.round(soldAcreag, 6));
		if (unsoldArea.compareTo(BigDecimal.ZERO) != 0)
			dsde.setUnsoldArea(unsoldArea);
		if (cwUnsoldParkinSpace.compareTo(BigDecimal.ZERO) != 0)
			dsde.setCwUnsoldParkinSpace(cwUnsoldParkinSpace.intValue());
		ProjectPremisesIndustDataDto queryIndust = new ProjectPremisesIndustDataDto();
		queryIndust.setProjectId(projectId);
		if (premisesId != null) {
			queryIndust.setPremisesId(premisesId);
			queryIndust.setIndustType("1");
		} else {
			queryIndust.setIndustType("0");
		}
		List<ProjectPremisesIndustData> industList = projectPremisesIndustDataService.selectListByDto(queryIndust);
		BigDecimal unit = new BigDecimal("10000");

		Date currerBeginDate = DateUtils.StringToDate(month);
		PmoSaleData currerPmoSaleData = queryPmoSaleData(projectId, premisesId, null, null, currerBeginDate, endDate);
		BigDecimal totalSignAmount = currerPmoSaleData.getTotalSignAmount();
		BigDecimal haveSignedAmount = currerPmoSaleData.getTotalHaveReceive();
		if (currerPmoSaleData.getTotalSignAmount() != null
				&& currerPmoSaleData.getTotalSignAmount().compareTo(BigDecimal.ZERO) != 0) {
			totalSignAmount = MathUtil.bigDivide(totalSignAmount, unit, 6);
			// 汇总实际销售额
			dsde.setActualSalesAmount(totalSignAmount.doubleValue());
		} else {
			dsde.setActualSalesAmount(new Double(BigDecimal.ZERO.toString()));
		}
		if (haveSignedAmount != null && haveSignedAmount.compareTo(BigDecimal.ZERO) != 0) {
			haveSignedAmount = MathUtil.bigDivide(haveSignedAmount, unit, 6);
			dsde.setActualBackAmount(haveSignedAmount.doubleValue());
		} else {
			dsde.setActualBackAmount(new Double(BigDecimal.ZERO.toString()));
		}
		if (null != industList && industList.size() > 0) { 
			// 面积目标销售均价汇总
			BigDecimal targetAveragPrice = BigDecimal.ZERO;
			// 车位目标销售均价汇总
			BigDecimal cwTargetAveragPrice = BigDecimal.ZERO;
			// 可售面积汇总
			BigDecimal salableAcreag = BigDecimal.ZERO;
			// 可售车位数汇总
			BigDecimal cwSalableAcreag = BigDecimal.ZERO;

			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
			Map<String, BaseCodeValueDto> bcvMap = baseCodeValueService.selectBcvMap(bcvDto);

			for (ProjectPremisesIndustData ppData : industList) {
				bcvDto = bcvMap.get(ppData.getIndustMark());
				// 车位
				if (bcvDto.getCodeValue().equals(IndustMarkEnums.INDUSTMARKENUMS_PARKINSPACE.getCode())) {
					if (ppData.getTargetAveragPrice() != null)
						cwTargetAveragPrice = cwTargetAveragPrice.add(ppData.getTargetAveragPrice());
					if (ppData.getSalableAcreag() != null)
						cwSalableAcreag = cwSalableAcreag.add(ppData.getSalableAcreag());
				} else { // 面积
					if (ppData.getTargetAveragPrice() != null)
						targetAveragPrice = targetAveragPrice.add(ppData.getTargetAveragPrice());
					if (ppData.getSalableAcreag() != null)
						salableAcreag = salableAcreag.add(ppData.getSalableAcreag());
				}

			}
			// 面积动态均价 =动态货值/可售面积
			if (roomDynamiValue.compareTo(BigDecimal.ZERO) != 0 && salableAcreag.compareTo(BigDecimal.ZERO) != 0) {
				dsde.setDynamiAveragPrice(
						MathUtil.bigDivide(roomDynamiValue, unit.multiply(salableAcreag), 6).doubleValue());
			}
			// 车位动态均价 = 车位动态货值/可售车位数
			if (cwTargetAveragPrice.compareTo(BigDecimal.ZERO) != 0
					&& cwUnsoldParkinSpace.compareTo(BigDecimal.ZERO) != 0) {
				BigDecimal result = carActualSalesAmount.add(cwTargetAveragPrice.multiply(cwUnsoldParkinSpace));
				dsde.setAveragPriceOfParkinSpace(MathUtil.bigDivide(result, cwSalableAcreag, 6).doubleValue());
			}
		

			
		}
		return dsde;
	}

	/**
	 * 
	 * createDynamiSalesDatas:组团的业态动态数据 <br/>
	 * 
	 * @author Administrator
	 * @param projectId
	 * @param month
	 * @return
	 * @since JDK 1.6
	 */
	public List<LevelDynamiSalesData> createDynamiSalesDatas(Long projectId, String month) {
		List<LevelDynamiSalesData> resultList = new ArrayList<LevelDynamiSalesData>();
		ProjectPremisesDto premisesDto = new ProjectPremisesDto();
		premisesDto.setProjectId(projectId);
		premisesDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<ProjectPremises> projectpremisesList = projectPremisesService.selectListByDto(premisesDto);
		if(null != projectpremisesList && projectpremisesList.size() > 0){
			/**
			 * PMO组团信息
			 */
			ProjectPremisesPmoDto pppDto = new ProjectPremisesPmoDto();
			pppDto.setProjectId(projectId);
			List<ProjectPremisesPmo> pppList = projectPremisesPmoService.selectListByDto(pppDto);
			Map<Long, ProjectPremisesPmo> pppMap = new HashMap<>();
			if(null != pppList && pppList.size() > 0){
				for(ProjectPremisesPmo ppp: pppList){
					pppMap.put(ppp.getPremisesId(), ppp);
				}
			}

			for (ProjectPremises premisesObj : projectpremisesList) {
				ProjectPremisesPmo projectPremisesPmo = pppMap.get(premisesObj.getId());
				if (null != projectPremisesPmo) {
					List<DynamiSalesDataExtend> list = createIndustDataList(projectId, premisesObj.getId(), "1", month);
					LevelDynamiSalesData levelDynamiSalesData = new LevelDynamiSalesData();
					levelDynamiSalesData.setPremisesId(premisesObj.getId());
					levelDynamiSalesData.setProjectCode(projectPremisesPmo.getPmoPremisesCode());
					levelDynamiSalesData.setLevel("phaseStaging");
					levelDynamiSalesData.setData(createDynamiSalesData(list, premisesObj.getId(), projectId, month));
					resultList.add(levelDynamiSalesData);
				}
			}
		}


		return resultList;
	}

	private PmoSaleData queryPmoSaleData(Long projectId, Long premisesId, String industMark, String isRoom,
			Date beginDate, Date endDate) {
		PmoSaleDataDto pmoSaleDataDto = new PmoSaleDataDto();
		if (null != projectId) {
			pmoSaleDataDto.setProjectId(projectId);
		}
		if (null != premisesId) {
			pmoSaleDataDto.setPremisesId(premisesId);
		}
		if (StringUtils.isNotBlank(industMark)) {
			pmoSaleDataDto.setIndustMark(industMark);
		}
		if (StringUtils.isNotBlank(isRoom)) {
			pmoSaleDataDto.setIsRoom(isRoom);
		}
		if (null != beginDate) {
			pmoSaleDataDto.setBeginDate(beginDate);
		}
		if (null != endDate) {
			pmoSaleDataDto.setEndDate(endDate);
		}
		PmoSaleData pmoSaleData = service.queryPmoSaleData(pmoSaleDataDto);
		return pmoSaleData;
	}

	/**
	 * 
	 * createIndustDataList:(这里用一句话描述这个方法的作用). <br/>
	 * 汇总项目-组团-业态动态数据 (7.11 修改,不需要汇总分期的业态数据得到 项目级的业态数据， 项目级的业态数据，自己新增)<br/>
	 * 
	 * @author Administrator
	 * @param projectId
	 * @param month
	 * @return
	 * @since JDK 1.6
	 */
	private List<DynamiSalesDataExtend> createIndustDataList(Long projectId, Long premisesId, String industType,
			String month) {

		Map<String, Date> dateMap = dateConvert(month);
		// 获取当月最后一天
		Date endDate = dateMap.get("endDate");
		// 开始时间
		Date beginDate = dateMap.get("beginDate");
		List<DynamiSalesDataExtend> resultList = new ArrayList<DynamiSalesDataExtend>();
		BigDecimal unit = new BigDecimal("10000");
		// 新逻辑，查询项目自己对应的所有业态信息
		ProjectPremisesIndustDataDto queryIndustData = new ProjectPremisesIndustDataDto();
		queryIndustData.setProjectId(projectId);
		queryIndustData.setIndustType(industType);
		queryIndustData.setPremisesId(premisesId);
		queryIndustData.setDelFlag(DelFlagEnum.UNDEL.getNo());
		List<ProjectPremisesIndustData> ppidList = projectPremisesIndustDataService.selectListByDto(queryIndustData);
		if(null != ppidList && ppidList.size() > 0){
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
			Map<String, BaseCodeValueDto> bcvMap = baseCodeValueService.selectBcvMap(bcvDto);

			for (ProjectPremisesIndustData ppid : ppidList) {
				String industMark = ppid.getIndustMark();
				if (StringUtils.isBlank(industMark)) {
					continue;
				}

				// 查询M2系统业态参数表
				bcvDto = bcvMap.get(industMark);
				if (null == bcvDto) {
					continue;
				}
				String pmoIndustMark = bcvDto.getCodeValue();
				DynamiSalesDataExtend dsde = new DynamiSalesDataExtend();
				dsde.setIndustValue(bcvDto.getCodeName());
				dsde.setIndustKey(bcvDto.getTypeName());
				dsde.setId(bcvDto.getId());
				dsde.setParentId(bcvDto.getTypeId());
				dsde.setProjectId(projectId);
				dsde.setIndustMark(pmoIndustMark);
				dsde.setMonth(month);
				beginDate = DateUtils.getCurrYearFirst();
				PmoSaleData pmoSaleData = queryPmoSaleData(projectId, premisesId, ppid.getIndustMark(), null, beginDate,
						endDate);
				if (premisesId == null) {
					System.out.println(bcvDto.getCodeName() + ":"
							+ DateUtils.DateToString(beginDate, DateStyle.YYYY_MM_DD_HH_MM_SS_CN.getValue()) + ","
							+ DateUtils.DateToString(endDate, DateStyle.YYYY_MM_DD_HH_MM_SS_CN.getValue()) + ","
							+ ppid.getIndustMark());
					System.err.println(JSONObject.toJSONString(pmoSaleData));
				}

				BigDecimal totalSignAmount = null;
				if (null != pmoSaleData.getTotalSignAmount()) {
					totalSignAmount = MathUtil.bigDivide(pmoSaleData.getTotalSignAmount(), unit, 6);
				}
				if (ppid.getTargetValue() == null) {
					ppid.setTargetValue(BigDecimal.ZERO);
				}
				if (pmoIndustMark.equals(IndustMarkEnums.INDUSTMARKENUMS_PARKINSPACE.getCode())) {
					// 已售车位数
					if (null != pmoSaleData.getTotalCalculateArea()
							&& pmoSaleData.getTotalCalculateArea().compareTo(BigDecimal.ZERO) != 0) {
						dsde.setSoldParkinSpace(pmoSaleData.getTotalCalculateArea().intValue());
					}
					// 未售车位 = 可售车位数-已售车位数
					if (pmoSaleData.getTotalCalculateArea() == null && ppid.getSalableAcreag() != null) {
						dsde.setTotalNoCalculateArea(ppid.getSalableAcreag());
					} else if (null != ppid.getSalableAcreag() && null != pmoSaleData.getTotalCalculateArea()) {
						dsde.setTotalNoCalculateArea(new BigDecimal(MathUtil.subtract(ppid.getSalableAcreag().doubleValue(),
								pmoSaleData.getTotalCalculateArea().doubleValue())));
					}
					// 车位动态货值=实际销售额+项目车位目标销售均价*未售车位数
					if (null != ppid.getTargetAveragPrice() && null != dsde.getTotalNoCalculateArea()) {
						if (totalSignAmount == null) {
							totalSignAmount = BigDecimal.ZERO;
						}
						double cwDynamiAveragPrice = MathUtil.add(totalSignAmount.doubleValue(), MathUtil.multiply(
								ppid.getTargetAveragPrice().doubleValue(), dsde.getTotalNoCalculateArea().doubleValue()));
						// 加自持货值
						dsde.setCwDynamiAveragPrice(new BigDecimal(cwDynamiAveragPrice));
					}
					// 车位动态均价=车位动态货值/可售车位数
					if (null != dsde.getCwDynamiAveragPrice() && null != ppid.getSalableAcreag()) {
						dsde.setAveragPriceOfParkinSpace(MathUtil
								.bigDivide(dsde.getCwDynamiAveragPrice(), ppid.getSalableAcreag(), 6).doubleValue());
					}
				} else {
					dsde.setTotalSalableAcreag(ppid.getSalableAcreag());
					// 动态货值=实际销售额+项目目标销售均价*未售面积
					// 未售面积
					BigDecimal notArea = null;
					// 已售面积
					BigDecimal convertTotalCalculateArea = null;
					if (pmoSaleData.getTotalCalculateArea() == null && ppid.getSalableAcreag() != null) {
						notArea = ppid.getSalableAcreag();
					} else if (null != ppid.getSalableAcreag() && null != pmoSaleData.getTotalCalculateArea()) {
						// 已售面积单位转换
						convertTotalCalculateArea = MathUtil.bigDivide(pmoSaleData.getTotalCalculateArea(), unit, 6);
						notArea = new BigDecimal(MathUtil.subtract(ppid.getSalableAcreag().doubleValue(),
								convertTotalCalculateArea.doubleValue()));
					}
					if (null != notArea && null != ppid.getTargetAveragPrice()) {
						// 动态货值
						if (totalSignAmount == null) {
							totalSignAmount = BigDecimal.ZERO;
						}
						double dynamiValue = MathUtil.add(totalSignAmount.doubleValue(), MathUtil
								.multiply(notArea.multiply(unit).doubleValue(), ppid.getTargetAveragPrice().doubleValue()));
						dsde.setDynamiValue(MathUtil.round(dynamiValue, 6));
					}
					// 已售面积
					dsde.setSoldAcreag(convertTotalCalculateArea == null ? null : convertTotalCalculateArea.doubleValue());
					// 未售面积
					dsde.setTotalNoCalculateArea(notArea);

					// 动态均价=动态货值/可售面积
					if (null != dsde.getDynamiValue() && null != ppid.getSalableAcreag()) {
						dsde.setDynamiAveragPrice(MathUtil
								.bigDivide(new BigDecimal(dsde.getDynamiValue()), ppid.getSalableAcreag().multiply(unit), 6)
								.doubleValue());
					}
				}
				//目标货值
				dsde.setTargetValue(targerValue(projectId, premisesId));
				// 实际销售额
				dsde.setMonthActualSalesAmount(
						totalSignAmount == null || totalSignAmount.compareTo(BigDecimal.ZERO) == 0 ? null
								: totalSignAmount);
				// 实际回款额
				if (null != pmoSaleData.getTotalHaveReceive()
						&& pmoSaleData.getTotalHaveReceive().compareTo(BigDecimal.ZERO) != 0) {
					dsde.setMonthActualBackAmount(MathUtil.bigDivide(pmoSaleData.getTotalHaveReceive(), unit, 6));
				}
				// 偏差原因
				dsde.setDeviationRemake(ppid.getDeviationRemake());
				resultList.add(dsde);
			}
		}
		return resultList;
	}
	
	public List<TargetValue> targerValue(Long projectId,Long premiseId){
		List<TargetValue> targetValueList = new ArrayList<>();
		if(projectId!=null && premiseId == null) {
			ProjectPmoDto projectPmoDto = new ProjectPmoDto();
			projectPmoDto.setProjectId(projectId);
			ProjectPmo projectPmo = projectPmoService.selectByDto(projectPmoDto);
			if(projectPmo.getTargetValue()!=null&&projectPmo.getTargetValueTime()!=null&&!StringUtils.isEmpty(projectPmo.getTargetValueVersion())){
			    TargetValue targetValue = new TargetValue();
			    targetValue.setTargetValue(projectPmo.getTargetValue().floatValue());
			    targetValue.setEffectStartTime(DateUtils.DateToString(projectPmo.getTargetValueTime(), DateStyle.YYYYMMDD.getValue()));
			    targetValue.setTargetValueVersion(projectPmo.getTargetValueVersion());
			    targetValueList.add(targetValue);
			}
		}else {
			ProjectPremisesPmoDto projectPremisesPmoDto = new ProjectPremisesPmoDto();
			projectPremisesPmoDto.setProjectId(projectId);
			projectPremisesPmoDto.setPremisesId(premiseId);
			ProjectPremisesPmo projectPremisesPmo = projectPremisesPmoService.selectByDto(projectPremisesPmoDto);
			if(projectPremisesPmo.getTargetValue()!=null && projectPremisesPmo.getTargetValueTime()!=null&& projectPremisesPmo.getTargetValueVersion() != null) {
				 TargetValue targetValue = new TargetValue();
				 targetValue.setTargetValue(projectPremisesPmo.getTargetValue().floatValue());
				 targetValue.setEffectStartTime(DateUtils.DateToString(projectPremisesPmo.getTargetValueTime(), DateStyle.YYYYMMDD.getValue()));
				 targetValue.setTargetValueVersion(projectPremisesPmo.getTargetValueVersion());
				 targetValueList.add(targetValue);
			}
		}
		return targetValueList;
	}

	@Override
	public Response<PmoSaleData> queryPmoSaleData(Long projectId, Long premisesId) {

		Response<PmoSaleData> response = new Response<PmoSaleData>();
		PmoSaleDataDto pmoSaleDataDto = new PmoSaleDataDto();
		if (null != projectId) {
			pmoSaleDataDto.setProjectId(projectId);
		}
		if (null != premisesId) {
			pmoSaleDataDto.setPremisesId(premisesId);
		}

		PmoSaleData pmoSaleData = service.queryPmoSaleData(pmoSaleDataDto);
		response.setEntity(pmoSaleData);
		return response;

	}

	public PmoSaleData selPmoSaleData(Long projectId, Long premisesId, String industMark, String isRoom) {
		PmoSaleDataDto pmoSaleDataDto = new PmoSaleDataDto();
		if (null != projectId) {
			pmoSaleDataDto.setProjectId(projectId);
		}
		if (null != premisesId) {
			pmoSaleDataDto.setPremisesId(premisesId);
		}
		if (StringUtils.isNotBlank(industMark)) {
			pmoSaleDataDto.setIndustMark(industMark);
		}
		if (StringUtils.isNotBlank(isRoom)) {
			pmoSaleDataDto.setIsRoom(isRoom);
		}
		PmoSaleData pmoSaleData = service.queryPmoSaleData(pmoSaleDataDto);
		return pmoSaleData;
	}

	@Override
	public PmoSaleData queryPmoArae(Long premisesId, String industMark) {
		PmoSaleDataDto pmoSaleDataDto = new PmoSaleDataDto();
		if (null != premisesId) {
			pmoSaleDataDto.setPremisesId(premisesId);
		}
		if (StringUtils.isNotBlank(industMark)) {
			pmoSaleDataDto.setIndustMark(industMark);
		}
		PmoSaleData pmoSaleData = service.queryPmoArae(pmoSaleDataDto);
		return pmoSaleData;
	}

	@Override
	public Response<LevelStaticIndustMark> levelStaticIndustMarkSum(LevelStaticIndustMarkParam param) {
		Response<LevelStaticIndustMark> response = new Response<LevelStaticIndustMark>();
		try {
			List<String> parkIdsList = new ArrayList<String>();
			LevelStaticIndustMark sum = projectPremisesIndustDataService.levelStaticIndustMarkSum(param, parkIdsList);
			response.success(sum);
		} catch (Exception e) {
			response.fail();
		}
		return response;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.estate.service.ProjectServiceFacade#updateProjectAndRoom(com.
	 * emm.yixun.common.model.dto.ProjectDto,
	 * com.emm.yixun.common.model.dto.ProjectPmoDto)
	 */
	@Override
	public Response<Boolean> updateProjectAndRoom(ProjectDto projectDto, ProjectPmoDto projectPmoDto) {
		Response<Boolean> response = new Response<Boolean>();
		response.setSuccess(Boolean.FALSE);
		try {
			if (StringUtils.isNotBlank(projectPmoDto.getPromotName())) {
				// 更新房间项目名称
				ProjectRoomDto projectRoomDto = new ProjectRoomDto();
				projectRoomDto.setProjectId(projectDto.getId());
				List<ProjectRoom> list = projectRoomService.selectListByDto(projectRoomDto);
				if (list != null && list.size() > 0) {
					ProjectRoomDto dto = new ProjectRoomDto();
					//dto.setProjectName(projectDto.getProjectName());
					dto.setProjectId(projectDto.getId());
					dto.setNewCombinedName(projectPmoDto.getPromotName());
					projectRoomService.updateCombinedNameByPid(dto);
				}
				// 项目名称为空,将项目名修改成推广名
				if(StringUtils.isBlank(projectDto.getProjectName())) {
					ProjectDto entity = new ProjectDto();
					entity.setId(projectDto.getId());
					entity.setProjectName(projectPmoDto.getPromotName());
					service.update(entity);
				}

				response.setEntity(Boolean.TRUE);
			}
		} catch (Exception e) {
			logger.error("更新项目名称与房间项目名称失败：" + e);
		}
		return response;
	}

	@Override
	public ResponseList<SaleReturnPmo> querySaleReturnListPmo(Long projectId, Long premisesId,
			SaleReturnEnum saleReturnEnum, String year) throws Exception {
		ResponseList<SaleReturnPmo> responseList = new ResponseList<SaleReturnPmo>();
		SaleReturnPmoDto srpDto = new SaleReturnPmoDto();
		srpDto.setSaleReturn(saleReturnEnum.getNo());
		if (StringUtils.isEmpty(year)) {
			srpDto.setSaleYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
		} else {
			srpDto.setSaleYear(year);
		}
		srpDto.setOrders("t.sale_month");
		srpDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		if (premisesId != null) { // 分期
			srpDto.setObjectType(ObjectTypeEnum.PREMISES.getNo());
			srpDto.setObjectId(premisesId);
		} else { // 项目
			srpDto.setObjectType(ObjectTypeEnum.PROJECT.getNo());
			srpDto.setObjectId(projectId);
		}
		List<SaleReturnPmo> saleReturnList = salereturnpmoservice.selectListByDto(srpDto);
		if (null != saleReturnList && saleReturnList.size() > 0) {
			BigDecimal unit = new BigDecimal("10000");
			for (SaleReturnPmo sale : saleReturnList) {
				// 实际销售额
				String month = sale.getSaleYear() + sale.getSaleMonth();
				Map<String, Date> dateMap = dateConvert(month);
				PmoSaleData pmoSaleData = queryPmoSaleData(projectId, premisesId, null, null,
						dateMap.get("beginDate"), dateMap.get("endDate"));
				BigDecimal totalSignAmount = null;
				if (null != pmoSaleData) {
					if (saleReturnEnum.getNo().equals("1")) {
						if (null != pmoSaleData.getTotalSignAmount()) {
							totalSignAmount = MathUtil.bigDivide(pmoSaleData.getTotalSignAmount(), unit, 6);
							sale.setSaleActual(totalSignAmount.toString());
						}
					} else {
						if (null != pmoSaleData.getTotalHaveReceive()) {
							totalSignAmount = MathUtil.bigDivide(pmoSaleData.getTotalHaveReceive(), unit, 6);
							sale.setSaleActual(totalSignAmount.toString());
						}
					}

					// 差额 = 计划 - 实际
					if (!StringUtils.isEmpty(sale.getSalePlan())) {
						if (totalSignAmount == null) {
							sale.setSaleDiff(sale.getSalePlan());
						} else {
							Double saleDiff = MathUtil.subtract(new Double(sale.getSalePlan()),
									totalSignAmount.doubleValue());
							sale.setSaleDiff(saleDiff.toString());
						}
					}
				}

			}
			responseList.setEntity(saleReturnList);
		}
		return responseList;
	}

	public static Map<String, Date> dateConvert(String month) {
		Map<String, Date> map = new HashMap<String, Date>();
		Date dateFormat = DateUtils.StringToDate(month, DateStyle.YYYYMM);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(dateFormat);
		calendar.set(Calendar.DAY_OF_MONTH, 1);
		Date firstDayOfMonth = calendar.getTime();
		calendar.add(Calendar.MONTH, 1);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		Date lastDayOfMonth = calendar.getTime();
		String beginDate = DateUtils.formatDate(firstDayOfMonth, DateStyle.YYYY_MM_DD.getValue()) + " 00:00:00";
		String endDate = DateUtils.formatDate(lastDayOfMonth, DateStyle.YYYY_MM_DD.getValue()) + " 23:59:59";
		map.put("beginDate", DateUtils.StringToDate(beginDate));
		map.put("endDate", DateUtils.StringToDate(endDate));
		return map;
	}

	@Override
	public HashMap<String, BigDecimal> queryDynamiValue(Long projectId, Long premiseId, String month,
			String industType) {
		HashMap<String, BigDecimal> map = new HashMap<String, BigDecimal>();
		try {
			ProjectPremisesIndustDataDto queryIndustData = new ProjectPremisesIndustDataDto();
			queryIndustData.setProjectId(projectId);
			queryIndustData.setIndustType(industType);
			queryIndustData.setPremisesId(premiseId);
			queryIndustData.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<ProjectPremisesIndustData> ppidList = projectPremisesIndustDataService
					.selectListByDto(queryIndustData);
			// 面积目标销售均价
			BigDecimal targetAveragPrice = BigDecimal.ZERO;
			// 车位目标销售均价
			BigDecimal cwtargetAveragPrice = BigDecimal.ZERO;
			// 可售面积
			BigDecimal salableAcreag = BigDecimal.ZERO;
			// 可售车位
			BigDecimal cwsalableAcreag = BigDecimal.ZERO;

			// 已售面积
			BigDecimal totalCalculateArea = BigDecimal.ZERO;
			// 已售车位
			BigDecimal cwtotalCalculateArea = BigDecimal.ZERO;
			// 面积实际销售额
			BigDecimal saleAmount = BigDecimal.ZERO;
			// 车位实际销售额
			BigDecimal cwSaleAmount = BigDecimal.ZERO;
			BigDecimal unit = new BigDecimal("10000");
			Map<String, Date> maps = dateConvert(month);
			Date beginDate = maps.get("beginDate");
			Date endDate = maps.get("endDate");
			for (ProjectPremisesIndustData data : ppidList) {
				BaseCodeValue baseCodeValue = baseCodeValueService.selectById(new Long(data.getIndustMark()));
				PmoSaleData pmoSaleData = queryPmoSaleData(projectId, premiseId, data.getIndustMark(), "", beginDate,
						endDate);
				// 车位
				if (baseCodeValue.getCodeValue().equals(IndustMarkEnums.INDUSTMARKENUMS_PARKINSPACE.getCode())) {

					if (pmoSaleData.getTotalCalculateArea() != null) {
						cwtotalCalculateArea = cwtotalCalculateArea.add(pmoSaleData.getTotalCalculateArea());
					}
					if (data.getTargetAveragPrice() != null) {
						cwtargetAveragPrice = cwtargetAveragPrice.add(data.getTargetAveragPrice());
					}
					if (data.getSalableAcreag() != null) {
						cwsalableAcreag = cwsalableAcreag.add(data.getSalableAcreag());
					}
					if (pmoSaleData.getTotalSignAmount() != null) {
						cwSaleAmount = cwSaleAmount.add(MathUtil.bigDivide(pmoSaleData.getTotalSignAmount(), unit, 6));
					}
				} else { // 面积
					if (data.getTargetAveragPrice() != null) {
						targetAveragPrice = targetAveragPrice.add(data.getTargetAveragPrice());
					}
					if (data.getSalableAcreag() != null) {
						salableAcreag = salableAcreag.add(data.getSalableAcreag());
					}
					if (pmoSaleData.getTotalCalculateArea() != null) {
						if (pmoSaleData.getTotalCalculateArea() != null) {
							totalCalculateArea = totalCalculateArea
									.add(MathUtil.bigDivide(pmoSaleData.getTotalCalculateArea(), unit, 6));
						}
					}
					if (pmoSaleData.getTotalSignAmount() != null) {
						saleAmount = saleAmount.add(MathUtil.bigDivide(pmoSaleData.getTotalSignAmount(), unit, 6));
					}
				}
			}
			// 动态货值 = 实际销售额+项目/分期目标销售均价*未售面积
			BigDecimal val = salableAcreag.subtract(totalCalculateArea);
			BigDecimal dyResult = saleAmount.add(targetAveragPrice.multiply(val.multiply(unit)));
			// 车位动态货值
			BigDecimal vals = cwsalableAcreag.subtract(cwtotalCalculateArea);
			BigDecimal cwdyResult = cwSaleAmount.add(cwtargetAveragPrice.multiply(vals));
			if (dyResult != null && dyResult.compareTo(BigDecimal.ZERO) != 0) {
				map.put("dynamiValue", new BigDecimal(MathUtil.round(dyResult, 6)));
			}
			if (cwdyResult != null && cwdyResult.compareTo(BigDecimal.ZERO) != 0) {
				map.put("cwdynamiValue", new BigDecimal(MathUtil.round(cwdyResult, 6)));
			}
			return map;
		} catch (Exception e) {
			logger.error("queryDynamiValue error", e);
		}
		return map;
	}

	/**
	 * 获取绑定过过问卷的项目
	 * 
	 * @param dto
	 * @return
	 */
	@Override
	public ResponseList<Project> getQuestionnaireProject(ProjectDto dto) {
		ResponseList<Project> response = new ResponseList<Project>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			if (null != dto.getNeedAuth() && "F".equals(dto.getNeedAuth())) {
				// 是否需要权限过滤，当值仅为F的时候，跳过
			} else {
				if (SysConstants.openDataPermission) {
					String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(),
							dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
					String[] dataPermissionArr = dataPermission.split(":");
					if ("00".equals(dataPermissionArr[0])) {
						response.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
						response.setSuccess(false);
						return response;
					}
					// 如果没有任何权限的时候
					String str = dataPermissionArr[1];
					if (StringUtils.isNotEmpty(str) && str.replace(" ", "").length() > 0) {
						dto.setDataPermission(dataPermissionArr[1]);
					} else {
						dto.setDataPermission("AND 1=2");
					}

				}
			}

			List<Project> list = service.getQuestionnaireProject(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<PmoReportDto> findIndustSalesData(Long projectId, String year) {
		Response<PmoReportDto> map = new Response<PmoReportDto>();
		List<GraphicalVo<BigDecimal>> list = new ArrayList<GraphicalVo<BigDecimal>>();
		List<GraphicalVo<BigDecimal>> list1 = new ArrayList<GraphicalVo<BigDecimal>>();
		try {
			// 业态销售额
			ProjectPremisesIndustDataDto entity = new ProjectPremisesIndustDataDto();
			entity.setProjectId(projectId);
			entity.setIndustType("0");
			List<ProjectPremisesIndustData> industList = projectPremisesIndustDataService.selectListByDto(entity);
			if (industList != null) {
				for (ProjectPremisesIndustData indust : industList) {
					// 业态每月的销售额
					GraphicalVo<BigDecimal> industDataSalesValue = new GraphicalVo<BigDecimal>();
					List<BigDecimal> idsValue = new ArrayList<BigDecimal>();
					BaseCodeValue baseCode = baseCodeValueService.selectById(new Long(indust.getIndustMark()));
					industDataSalesValue.setName(baseCode.getCodeName());
					String minDate = DateUtils.DateToString(DateUtils.StringToDate(year + "01"),
							DateStyle.YYYYMM.getValue());
					String maxDate = DateUtils.DateToString(DateUtils.StringToDate(year + "12"),
							DateStyle.YYYYMM.getValue());
					List<String> dateList = DateUtils.getMonthBetween(minDate, maxDate);
					List<BigDecimal> idsValueindust = new ArrayList<BigDecimal>();
					for (int i = 0; i < dateList.size(); i++) {
						Map<String, Date> maps = dateConvert(dateList.get(i));
						Date beginDate = maps.get("beginDate");
						Date endDate = maps.get("endDate");
						PmoSaleData saleData = queryPmoSaleData(projectId, null, indust.getIndustMark(), null,
								beginDate, endDate);
						idsValue.add(saleData.getTotalSignAmount() == null ? BigDecimal.ZERO
								: MathUtil.bigDivide(saleData.getTotalSignAmount(), new BigDecimal("10000"), 6));
						idsValueindust.add(new BigDecimal(getIndustDataSource(year, endDate, indust, baseCode)));
					}
					GraphicalVo<BigDecimal> industDataVal = new GraphicalVo<BigDecimal>(baseCode.getCodeName(),
							idsValueindust);
					list1.add(industDataVal);
					industDataSalesValue.setData(idsValue);
					list.add(industDataSalesValue);
				}
				PmoReportDto dto = new PmoReportDto(list, list1);
				map.setEntity(dto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询数据错误：{}", e);
		}
		return map;
	}

	public Double getIndustDataSource(String year, Date endDate, ProjectPremisesIndustData ppid,
			BaseCodeValue baseCodeValue) {
		Double dynamiValueResult = null;
		BigDecimal totalSignAmount = null;
		BigDecimal unit = new BigDecimal("10000");
		String y = year + "-01-01 00:00:00";
		PmoSaleData pmoSaleData = queryPmoSaleData(ppid.getProjectId(), null, baseCodeValue.getId().toString(), null,
				DateUtils.StringToDate(y), endDate);
		if (null != pmoSaleData.getTotalSignAmount()) {
			totalSignAmount = MathUtil.bigDivide(pmoSaleData.getTotalSignAmount(), unit, 6);
		}
		if (IndustMarkEnums.INDUSTMARKENUMS_PARKINSPACE.getCode().equals(baseCodeValue.getCodeValue())) {
			BigDecimal noCar = null;
			if (pmoSaleData.getTotalCalculateArea() == null && ppid.getSalableAcreag() != null) {
				noCar = ppid.getSalableAcreag();
			} else if (null != ppid.getSalableAcreag() && null != pmoSaleData.getTotalCalculateArea()) {
				noCar = new BigDecimal(MathUtil.subtract(ppid.getSalableAcreag().doubleValue(),
						pmoSaleData.getTotalCalculateArea().doubleValue()));
			}
			if (null != ppid.getTargetAveragPrice() && null != noCar) {
				if (totalSignAmount == null) {
					totalSignAmount = BigDecimal.ZERO;
				}
				double cwDynamiAveragPrice = MathUtil.add(totalSignAmount.doubleValue(),
						MathUtil.multiply(ppid.getTargetAveragPrice().doubleValue(), noCar.doubleValue()));
				// 加自持货值
				dynamiValueResult = cwDynamiAveragPrice;
			}
		} else {
			BigDecimal notArea = null;
			// 已售面积
			BigDecimal convertTotalCalculateArea = null;
			if (pmoSaleData.getTotalCalculateArea() == null && ppid.getSalableAcreag() != null) {
				notArea = ppid.getSalableAcreag();
			} else if (null != ppid.getSalableAcreag() && null != pmoSaleData.getTotalCalculateArea()) {
				// 已售面积单位转换
				convertTotalCalculateArea = MathUtil.bigDivide(pmoSaleData.getTotalCalculateArea(), unit, 6);
				notArea = new BigDecimal(MathUtil.subtract(ppid.getSalableAcreag().doubleValue(),
						convertTotalCalculateArea.doubleValue()));
			}
			if (null != notArea && null != ppid.getTargetAveragPrice()) {
				// 动态货值
				if (totalSignAmount == null) {
					totalSignAmount = BigDecimal.ZERO;
				}
				double dynamiValue = MathUtil.add(totalSignAmount.doubleValue(), MathUtil
						.multiply(notArea.multiply(unit).doubleValue(), ppid.getTargetAveragPrice().doubleValue()));
				dynamiValueResult = MathUtil.round(dynamiValue, 6);
			}
		}
		return dynamiValueResult;
	}

	@Override
	public boolean checkPmoPush(String pmoProjectCode) {
		/**
		 * 校验一下项目是否需要推送PMO数据
		 */
		boolean pmoPushFlag = true;
		ProjectPmoDto ppDto = new ProjectPmoDto();
		ppDto.setPmoProjectCode(pmoProjectCode);
		ProjectPmo pp = projectPmoService.selectByDto(ppDto);
		if(null != pp){
			Project project = service.selectById(pp.getProjectId());
			if(null != project){
				String pmoPush = project.getPmoPush();
				if (PmoPushEnum.NO_PUSH.getNo().equals(pmoPush)) {
					pmoPushFlag = false;
				}
			}
		}
		return pmoPushFlag;
	}
}
